#include "aiservermanager.h"

AiServerManager::AiServerManager(QWidget *parent) : QWidget(parent),
    networkManager(new QNetworkAccessManager(this))
{
    this->apiKey = "2cb13f1e318b4fae8e7a8eac5ed7a93b.azYqiNwTqKrlZvMs";
    this->apiUrl = "https://open.bigmodel.cn/api/paas/v4/chat/completions";

    connect(this->networkManager, &QNetworkAccessManager::finished, this, &AiServerManager::onReplyFinished);

}

void AiServerManager::sendMassge(QString message)
{
    if (message.trimmed().isEmpty()) // 去除字符串中的空白符号后，在检测是否为空
    {
        emit errorOccured("密码不能为空");
        return;
    }
    // 构造请求JSON
    QJsonObject requestBody;
    requestBody["model"] = "glm-4.5-flash";
    QJsonArray messages;
    requestBody["messages"] = messages;
    QJsonObject systemMessage;
    systemMessage["role"] = "system";
    systemMessage["content"] = "你是一个有用的AI助手。";
    QJsonObject userMessage;
    userMessage["role"] = "user";
    userMessage["content"] = "请介绍一下人工智能的发展历程。";
    messages.append(systemMessage);
    messages.append(userMessage);
    requestBody["temperature"] = 1;
    //requestBody["max_tokens"] = 65536;
    requestBody["stream"] = false;


    QJsonDocument doc(requestBody);
    QByteArray data = doc.toJson();

    // 设置网络请求
    QNetworkRequest request;
    request.setUrl(QUrl(apiUrl));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    request.setRawHeader("Authorization", QString("Bearer %1").arg(apiKey).toUtf8()); // QString("Bearer %1").arg(apiKey).toUtf8()),将%1的占位符替换为arg(apikey).toUtf8()

    // 发送请求
    this->networkManager->post(request, data);
}

void AiServerManager::onReplyFinished(QNetworkReply *reply)
{
    if (reply->error() != QNetworkReply::NoError) {
        emit errorOccured (reply->errorString());
        reply->deleteLater();
        return;
    }

    QByteArray responseData = reply->readAll();
    reply->deleteLater();

    // 解析JSON响应
    QJsonDocument doc = QJsonDocument::fromJson(responseData);
    if (doc.isNull()) {
        emit errorOccured("解析响应失败");
        return;
    }

    QJsonObject json = doc.object();
    if (json.contains("error")) {
        QString errorMsg = json["error"].toObject()["message"].toString();
        emit errorOccured(errorMsg);
        return;
    }

    // 提取AI回复内容
    QString aiResponse;
    if (json.contains("choices")) {
        QJsonArray choices = json["choices"].toArray();
        if (!choices.isEmpty()) {
            QJsonObject choice = choices[0].toObject();
            QJsonObject message = choice["message"].toObject();
            aiResponse = message["content"].toString().trimmed();
        }
    }

    if (aiResponse.isEmpty()) {
        emit errorOccured("无法获取AI回复");
    } else {
        emit resposeReceive(aiResponse);
    }
}
